package com.example.myapplication.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.example.myapplication.BaseOnclickListener;
import com.example.myapplication.R;
import com.example.myapplication.entity.SearchResult;

import java.util.List;

public class ResultAlbumAdapter extends RecyclerView.Adapter<ResultAlbumAdapter.ResultAlbumViewHolder> {
    private BaseOnclickListener onclickListener;
    private List<SearchResult.AlbumsBean> albums;
    private Context context;

    public ResultAlbumAdapter(Context context) {
        this.context = context;
    }

    public void setData(List<SearchResult.AlbumsBean> albums){
        this.albums = albums;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ResultAlbumViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ResultAlbumViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_result_album, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull ResultAlbumViewHolder holder, int position) {
        SearchResult.AlbumsBean albumsBean = albums.get(position);

        Glide.with(context)
                .load(albumsBean.getPicUrl())
                .apply(RequestOptions.bitmapTransform(new RoundedCorners(40)))
                .into(holder.img);

        holder.tvAlbumName.setText(albumsBean.getName());
        holder.tvSingerName.setText(albumsBean.getArtist().getName());
        holder.view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onclickListener != null){
                    onclickListener.click(position);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return albums == null ? 0 : albums.size();
    }

    class ResultAlbumViewHolder extends RecyclerView.ViewHolder{
        ImageView img;
        TextView tvAlbumName;
        TextView tvSingerName;
        View view;

        public ResultAlbumViewHolder(@NonNull View itemView) {
            super(itemView);
            img = itemView.findViewById(R.id.album_cover);
            tvAlbumName = itemView.findViewById(R.id.tv_album_name);
            tvSingerName = itemView.findViewById(R.id.tv_singer_name);
            view = itemView.findViewById(R.id.view_layout);
        }
    }

    public void setBaseOnclickListener(BaseOnclickListener onclickListener){
        this.onclickListener = onclickListener;
    }
}
